<template>
  <div class="upload-video flex" :class="props.rounded ? 'rounded' : ''">
    <a-space wrap>
      <!-- 单视频 -->
      <div :class="'video-list ' + (props.rounded ? 'rounded' : '')" v-if="!props.multiple && currentItem?.url">
        <a-button class="delete" @click="removeSignImage()">
          <template #icon>
            <icon-delete />
          </template>
        </a-button>
        <video 
          controls
          width="240"
          height="135"
          :class="props.rounded ? 'rounded' : ''"
          :src="currentItem.url"
        >
          <source :src="currentItem.url" type="video/mp4">
        </video>
      </div>

      <!-- 多视频 -->
      <template v-else-if="props.multiple">
        <div :class="'video-list ' + (props.rounded ? 'rounded' : '')" v-for="(video, idx) in showImgList" :key="idx">
          <a-button class="delete" @click="removeImage(idx)">
            <template #icon>
              <icon-delete />
            </template>
          </a-button>
          <video 
            controls
            width="240"
            height="135"
            :class="props.rounded ? 'rounded' : ''"
            :src="video.url"
          >
            <source :src="video.url" type="video/mp4">
          </video>
        </div>
      </template>

      <a-upload
        v-if="props.multiple || !currentItem?.url"
        :custom-request="uploadVideoHandler"
        :show-file-list="false"
        :accept="props.accept"
        :disabled="props.disabled"
        :tip="props.tip">
        <template #upload-button>
          <slot name="customer">
            <div :class="'upload-skin ' + (props.rounded ? 'rounded' : '')">
              <div class="icon text-3xl">
                <icon-video />
              </div>
              <div class="title">
                {{ props.title || '上传视频' }}
              </div>
            </div>
          </slot>
        </template>
      </a-upload>
    </a-space>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { isArray } from 'lodash'
import file2md5 from 'file2md5'
import commonApi from '@/api/common'
import { Message } from '@arco-design/web-vue'

const props = defineProps({
  modelValue: {
    type: [String, Number, Array],
    default: () => {},
  },
  rounded: { type: Boolean, default: false },
  multiple: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  title: { type: String, default: '本地上传' },
  icon: { type: String, default: 'icon-video' },
  size: { type: Number, default: 100 * 1024 * 1024 }, // 默认100MB
  limit: { type: Number, default: 0 },
  mode: { type: String, default: 'system' },
  tip: { type: String, default: '支持格式：MP4/MOV/AVI，最大50MB' },
  accept: { 
    type: String, 
    default: '.mp4,.mov,.avi,.wmv,.flv,.mkv' 
  },
})

const emit = defineEmits(['update:modelValue'])

const showImgList = ref([])
const signImage = ref()
const currentItem = ref({})

const uploadVideoHandler = async (options) => {
  if (!options.fileItem) return
  
  const file = options.fileItem.file
  if (file.size > props.size) {
    Message.warning(`文件大小不能超过 ${props.size / 1024 / 1024}MB`)
    return
  }

  if (props.multiple && props.limit > 0 && showImgList.value.length >= props.limit) {
    Message.warning(`最多上传 ${props.limit} 个视频`)
    return
  }

  try {
    const hash = await file2md5(file)
    const formData = new FormData()
    formData.append('video', file)
    formData.append('hash', hash)
    formData.append('isChunk', false)
    
    if (props.mode === 'local') {
      formData.append('mode', 'local')
    }

    const { data } = await commonApi.uploadVideo(formData)
    
    if (props.multiple) {
      showImgList.value.push(data)
      emit('update:modelValue', showImgList.value.map(item => item.url))
    } else {
      currentItem.value = data
      signImage.value = data.url
      emit('update:modelValue', data.url)
    }
  } catch (error) {
    Message.error('视频上传失败')
  }
}
const removeSignImage = () => {
  currentItem.value = {}
  signImage.value = undefined
  emit('update:modelValue', null)
}

const removeImage = (idx) => {
  showImgList.value.splice(idx, 1)
  let files = []
  files = showImgList.value.map((item) => {
    return item['url']
  })
  emit('update:modelValue', files)
}

const initData = async () => {
  if (props.multiple) {
    if (isArray(props.modelValue) && props.modelValue.length > 0) {
      showImgList.value = props.modelValue.map((url) => {
        return { url }
      })
    } else {
      showImgList.value = []
    }
  } else if (props.modelValue) {
    signImage.value = props.modelValue
    currentItem.value.url = props.modelValue
    currentItem.value.percent = 100
    currentItem.value.status = 'complete'
  } else {
    removeSignImage()
  }
}
watch(
  () => props.modelValue,
  (val) => {
    initData()
  },
  {
    deep: true,
    immediate: true,
  }
)



</script>

<style lang="less" scoped>
.video-list {
  position: relative;
  width: 240px;
  height: 135px;
  margin-right: 12px;
  margin-bottom: 12px;
  
  video {
    width: 100%;
    height: 100%;
    object-fit: cover;
    background: #000;
    border-radius: 4px;
  }

  .delete {
    position: absolute;
    z-index: 99;
    right: 3px;
    top: 3px;
    display: none;
  }

  &:hover .delete {
    display: block;
  }
}

.upload-skin {
  width: 240px;
  height: 135px;
  background: var(--color-fill-2);
  border: 1px dashed var(--color-fill-4);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;

  &:hover {
    border-color: rgb(var(--primary-6));
    
    .icon, .title {
      color: rgb(var(--primary-6));
    }
  }

  .icon {
    font-size: 24px;
    color: var(--color-text-3);
  }

  .title {
    margin-top: 8px;
    color: var(--color-text-3);
    font-size: 12px;
  }
}
</style>